import * as echarts from 'echarts';
import React, { useRef, useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import emitter from '#/utils/events';

export default function Chart({
  config = {},
  height = 400,
  header,
  footer,
  onLegendChange = null,
}) {
  const chartRef = useRef(null);
  let [chartIns, setChartIns] = useState(null);

  useEffect(() => {
    chartIns = echarts.init(chartRef.current);
    if (typeof onLegendChange === 'function') {
      chartIns.on('legendselectchanged', (obj) => {
        obj.selected && onLegendChange?.(obj);
      });
    }
    setChartIns(chartIns);
    window.addEventListener('resize', _onHandleResize);
    emitter.addListener('onChangeMnue', _onHandleResize);
    return () => {
      window.removeEventListener('resize', _onHandleResize);
      emitter.removeListener('onChangeMnue', _onHandleResize);
      chartIns?.off('legendselectchanged');
      chartIns?.dispose();
      chartIns = null;
    };
  }, []);

  useEffect(() => {
    if (chartIns && config) {
      chartIns?.setOption(config, true);
      chartIns?.resize();
    }
  }, [config]);

  function _onHandleResize() {
    setTimeout(() => {
      chartIns?.resize();
    }, 500);
  }

  return (
    <div style={{ position: 'relative', width: '100%', height }}>
      {header}
      <div style={{ width: '100%', height }} ref={chartRef} />
      {footer}
    </div>
  );
}

Chart.propTypes = {
  config: PropTypes.any,
  height: PropTypes.any,
  header: PropTypes.any,
  footer: PropTypes.any,
  onLegendChange: PropTypes.any,
};
